<?php

namespace app\api\controller;

use app\api\model\UserCoupons;
use app\api\model\Users;
use app\api\model\UserVip;
use app\api\model\Wechat;
use app\common\controller\Api;
use think\Controller;
use think\Db;
use think\Request;
use app\api\model\RealOrder as RealOrderModel;
use Yansongda\Pay\Exceptions\GatewayException;

class RealOrder extends Api
{
    protected $noNeedLogin = ['paymentResult'];
    protected $noNeedRight = ['*'];

    /**
     * 支付
     */
    public function pay($order_id, Wechat $wechat)
    {
        $order = RealOrderModel::find($order_id);
        $type = $this->request->post('type');
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->status == 2) {
            $this->success('订单已支付', ['order_id' => $order_id]);
        }
        if ($order->real_amount <= 0) {
            $this->error('支付金额必须大于0');
        }

        $user = Users::find($this->auth->getUserId());
        if (!$user) {
            $this->error('用户不存在');
        }
        //可能新用户
        if (!$order->user_id) {
            $order->user_id = $user->id;
            $res = $order->save();
            if (!$res) {
                $this->error('订单异常，请联系管理员');
            }
        }
        switch ($type) {
            //余额
            case 1:
                if ($user->money < $order->real_amount) {
                    $this->error('余额不足，请先充值');
                }
                $this->paySuccess($order, $user, 'account');
                break;
            case 2:
                try {
                    $order->total_amount = $order->real_amount;
                    $res = $wechat->miniapp($order, $user->openid, config('wechat.notify_url'));
                } catch (\Exception $e) {
                    throw new GatewayException($e->getMessage(), $e->getCode());
                }
                $res['order_no'] = $order->order_no;
                isset($e) ? $this->error('支付失败，请联系管理员') : $this->success('请求成功', $res);
                break;
            default:
                $this->error('支付类型无效');
                break;

        }
    }

    /**
     * 支付回调
     */
    public function notify(Wechat $wechat)
    {
        $order_no = $this->request->post('order_no');
        if (empty($order_no)) {
            $this->error('订单号不能为空');
        }
        $order = RealOrderModel::getByOrderNo($order_no);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->status == 2) {
            $this->success('支付成功', ['order_id' => $order->id]);
        }
        //查询支付结果
        $res = $wechat->find($order_no);
        if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
            if ($res['trade_state'] === 'SUCCESS') {
                $user = Users::find($order['user_id']);
                $this->paySuccess($order, $user, 'wechat');
            } else {
                $this->error($res['trade_state_desc'], [], $res['trade_state']);
            }
        } else {
            $this->error('支付失败，请联系管理员');
        }

    }

    /**
     * 支付结果通知
     */
    public function paymentResult(Wechat $wechat)
    {
        $res = $wechat->verify();
        if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
            $order = RealOrderModel::getByOrderNo($res['out_trade_no']);
            if ($order && $order->status == 1) {
                $user = Users::find($order['user_id']);
                $this->paySuccess($order, $user, 'wechat');
            }
        }
        $wechat->wechatPay()->success()->send();
    }

    public function paySuccess($order, $user, $type)
    {
        Db::startTrans();
        try {
            //订单
            $order->status = 2;
            $order->type = $type;
            if (!$order->user_id) {
                $order->user_id = $user->id;
            }
            $order->save();
            //优惠券核销
            if ($order->user_coupon_id) {
                UserCoupons::where('id', $order->user_coupon_id)->update(['status' => 2]);
            }
            //扣除余额
            if ($type == 'account') {
                $user->money -= $order->real_amount;
            }
            //累积消费额
            $user->expense_money += $order->real_amount;
            $user->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        isset($e) ? $this->error('支付失败，请联系管理员') : $this->success('支付成功', ['order_id' => $order->id]);
    }

    /**
     * 支付信息
     */
    public function info($order_id)
    {
        $order = RealOrderModel::with(['user', 'service'])->find($order_id);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->real_amount <= 0) {
            $this->error('订单支付金额为0，请联系管理员确认');
        }
        if ($order->service) {
            foreach ($order['service'] as $val) {
                if ($order->user && $order->user->vip) {
                    $discount = UserVip::getDiscountByName($order->user->vip);
                    $val['price'] = number_format($val['price'] * $discount / 100, 2) ;
                }
            }
        }

        $this->success('请求成功', compact('order'));
    }

}
